#include <stdio.h>
#include <string.h>
#include "protocol.h"

/* 测试缓冲区大小 */
#define TEST_BUF_SIZE 1024

/* 测试数据 */
static uint8_t test_buf[TEST_BUF_SIZE];
static uint8_t pack_buf[TEST_BUF_SIZE];

/* 打印十六进制数据 */
static void print_hex(const uint8_t *data, int len)
{
    int i;
    for (i = 0; i < len; i++) {
        printf("%02X ", data[i]);
    }
    printf("\n");
}

/* 正向测试用例 */
static void test_normal_case(void)
{
    proto_parser_t parser;
    const char *test_data = "Hello World";
    int i, len;
    bool ret;
    
    printf("\n=== Normal Test Cases ===\n");
    
    /* 初始化解析器 */
    proto_parser_init(&parser, test_buf, TEST_BUF_SIZE);
    
    /* 打包数据 */
    len = proto_pack(pack_buf, TEST_BUF_SIZE, CMD_GET_DEVICE_INFO, 
                    (const uint8_t *)test_data, strlen(test_data));
    
    printf("Packed data (%d bytes): ", len);
    print_hex(pack_buf, len);
    
    /* 逐字节解析 */
    for (i = 0; i < len; i++) {
        ret = proto_parse_byte(&parser, pack_buf[i]);
        if (ret) {
            printf("Parse complete!\n");
            printf("Command: 0x%02X\n", parser.cmd);
            printf("Data (%d bytes): ", parser.data_len);
            print_hex(parser.buf, parser.data_len);
        }
    }
}

/* 异常测试用例 */
static void test_error_case(void)
{
    proto_parser_t parser;
    const char *test_data = "Hello World";
    uint8_t bad_pack[TEST_BUF_SIZE];
    int i, len;
    bool ret;
    
    printf("\n=== Error Test Cases ===\n");
    
    /* 初始化解析器 */
    proto_parser_init(&parser, test_buf, TEST_BUF_SIZE);
    
    /* 1. 错误的帧头 */
    len = proto_pack(pack_buf, TEST_BUF_SIZE, CMD_GET_DEVICE_INFO,
                    (const uint8_t *)test_data, strlen(test_data));
    memcpy(bad_pack, pack_buf, len);
    bad_pack[0] = 0x55; /* 修改帧头 */
    
    printf("Test wrong header:\n");
    for (i = 0; i < len; i++) {
        ret = proto_parse_byte(&parser, bad_pack[i]);
        if (ret) {
            printf("ERROR: Should not parse success!\n");
        }
    }
    
    /* 2. 错误的CRC */
    proto_parser_init(&parser, test_buf, TEST_BUF_SIZE);
    memcpy(bad_pack, pack_buf, len);
    bad_pack[len-1] = 0x00; /* 修改CRC */
    
    printf("Test wrong CRC:\n");
    for (i = 0; i < len; i++) {
        ret = proto_parse_byte(&parser, bad_pack[i]);
        if (ret) {
            printf("ERROR: Should not parse success!\n");
        }
    }
    
    /* 3. 数据长度超限 */
    printf("Test data too long:\n");
    ret = proto_pack(pack_buf, TEST_BUF_SIZE, CMD_GET_DEVICE_INFO,
                    (const uint8_t *)test_data, TEST_BUF_SIZE + 1);
    if (ret != -1) {
        printf("ERROR: Should return error!\n");
    }
}

int main(void)
{
    /* 运行测试用例 */
    test_normal_case();
    test_error_case();
    
    return 0;
} 